package controllers

import (
	"gin-AssetManagement/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func MenusView(g *gin.Context) {
	g.HTML(http.StatusOK, "menu/index.html", nil)
}
func CreateMenusView(g *gin.Context) {
	g.HTML(http.StatusOK, "menu/create.html", nil)
}
func MenusList(g *gin.Context) {
	menusList, count, err := models.GetMenusList()
	var m models.MenusJson
	loadmenus := models.LoadMenu(&m, menusList)
	if err != nil {
		g.JSON(http.StatusNotFound, LayuiData{
			Code:  1,
			Msg:   "获取数据失败",
			Count: 0,
			Data:  nil,
		})
		return
	}
	g.JSON(http.StatusOK, LayuiData{
		Code:  0,
		Msg:   "成功",
		Count: count,
		Data:  loadmenus,
	})
}

// CreateMenus 添加菜单
// @Summary 添加菜单
// @Schemes http
// @Tags 添加菜单
// @Description 添加菜单
// @Accept json
// @Produce json
// @Param name query string true "菜单名称"
// @param url query string true "rul"
// @param icon query string true "图标"
// @param parent_id query string true "父节菜单id"
// @param ParentName query string true "父菜单名称"
// @param level query int true "层级"
// @param type query int true "类型"
// @param order query int true "顺序编号"
// @Success 200 {json} {"code":0,"msg":"成功"}
// @Router /menus/createMenus [post]
func CreateMenus(g *gin.Context) {
	var menus models.Menus
	if err := g.ShouldBind(&menus); err != nil {
		g.JSON(400, gin.H{"error": err.Error()})
		return
	}
	err := menus.CreateMenus()
	if err != nil {
		g.JSON(400, Respond{
			Code: 1,
			Msg:  "添加菜单失败",
			Data: err.Error(),
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "添加菜单成功",
		Data: nil,
	})
}
func DelMenus(g *gin.Context) {
	id := g.Param("id")
	inint, _ := strconv.ParseUint(id, 10, 32)
	var menus models.Menus
	menus.ID = uint(inint)
	err := menus.DelMneus()
	if err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "删除失败",
			Data: nil,
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "删除成功",
		Data: nil,
	})

}

type UpdateJson struct {
	Field string `json:"field"`
	Value string `json:"value"`
}

func UpdateMenus(g *gin.Context) {
	id := g.Param("id")
	field := g.PostForm("field")
	value := g.PostForm("value")
	inint, _ := strconv.ParseUint(id, 10, 32)
	var menus models.Menus
	menus.ID = uint(inint)
	err := menus.UpdateMenus(field, value)
	if err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "修改失败",
			Data: nil,
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "修改成功",
		Data: nil,
	})
}
func GetMenusTreeList(g *gin.Context) {
	menusList, _, err := models.GetMenusList()
	if err != nil {
		g.JSON(http.StatusOK, err.Error())
		return
	}
	roletree := models.RoleTree{}
	rtd := models.RoleTreeData(&roletree, menusList)
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "成功",
		Data: rtd,
	})
}
